package com.i2bt.app.set.model;

import com.i2bt.common.AndroidRestContract;
import com.i2bt.common.UserConfig;

import com.i2bt.app.BaseActivity;
import com.i2bt.app.BaseJsonModel;
import com.i2bt.app.set.AuthoritySetActivity;
import com.i2bt.view.SwitchButton;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GetHomeBoxListJsonHandle extends BaseJsonModel {
	private AuthoritySetActivity act;
	private String homeBoxId[];
	private boolean homeBoxOn[];
	private String homeboxName[];

	public String[] getHomeBoxId() {
		return homeBoxId;
	}

	public GetHomeBoxListJsonHandle(BaseActivity activity) {
		super(activity);
		act = (AuthoritySetActivity) activity;
		// TODO Auto-generated constructor stub
	}

	@Override
	protected String logicToWrap() {
		// TODO Auto-generated method stub
		try {
			jsonParam.put(AndroidRestContract.ACTION,
					AndroidRestContract.GET_HOMEBOX_LIST);
			jsonParam.put(AndroidRestContract.TOKEN, UserConfig.token);
			System.out.println("HomeBoxTOKEN:" + UserConfig.token);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return jsonParam.toString();
	}

	@Override
	protected void logicToUnwrap(boolean isSuc, String result) {
		// TODO Auto-generated method stub
		System.out.println(result);
		if (isSuc) {
			try {
				JSONObject ja = new JSONObject(result);
				boolean succ = ja.getBoolean(AndroidRestContract.SUCCEED);
				if (succ) {
					JSONArray homeboxlist = ja
							.getJSONArray(AndroidRestContract.HOMEBOX_LIST);
					int length = homeboxlist.length();
					homeBoxId = new String[length];
					homeboxName = new String[length];
					homeBoxOn = new boolean[length];
					act.switchBtu = new SwitchButton[length];
					for (int i = 0; i < length; i++) {
						JSONObject obj = homeboxlist.getJSONObject(i);
						homeboxName[i] = obj
								.getString(AndroidRestContract.HOMEBOX_NAME);
						homeBoxId[i] = obj
								.getString(AndroidRestContract.HOMEBOX_ID);
						if (obj.getString(AndroidRestContract.HOMEBOX_POWER)
								.equals("on")) {
							homeBoxOn[i] = true;
						} else {
							homeBoxOn[i] = false;
						}
					}
					this.act.setList(homeboxName, homeBoxOn);
					System.out.println("长度:" + length);
				} else {
					String mes = ja.getString(AndroidRestContract.MESSAGE);
					this.activity.toastHandler(mes);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			this.activity.toastHandler("网络连接失败");
		}
	}
}
